package com.project.myxima.fragments;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Rect;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.project.myxima.MainActivity;
import com.project.myxima.PlayerActivity;
import com.project.myxima.R;
import com.project.myxima.adapters.DetailAdapter;
import com.project.myxima.base.BaseApplication;
import com.project.myxima.interfaces.IHistoryViewCallback;
import com.project.myxima.presenters.HistoryPresenter;
import com.project.myxima.presenters.PlayerPresenter;
import com.project.myxima.utils.LogUtils;
import com.project.myxima.views.HistoryTrackDialog;
import com.project.myxima.views.UILoader;
import com.ximalaya.ting.android.opensdk.model.track.Track;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import java.util.List;

public class HistoryFragment extends BaseFragment implements HistoryTrackDialog.OnDialogActionClickListener , IHistoryViewCallback {

    private static final String TAG = "HistoryFragment";
    private UILoader mUILoader;
    private RecyclerView mHistory_rv;
    private DetailAdapter mHistoryAdapter;
    private Track mCurrentTrack;
    private HistoryTrackDialog mTrackDialog;
    private HistoryPresenter mHistoryPresenter;

    @Override
    protected View onSubViewLoaded(LayoutInflater layoutInflater, ViewGroup container) {
        View rootView = layoutInflater.inflate(R.layout.fragment_history, container, false);
        FrameLayout historyContainer = rootView.findViewById(R.id.history_container);

        mUILoader = new UILoader(container.getContext()) {
            @Override
            protected View getSuccessView(ViewGroup container) {
                return initSuccessView(layoutInflater, container);
            }
        };

        if (mUILoader.getParent() instanceof ViewGroup) {
            ((ViewGroup) mUILoader.getParent()).removeView(mUILoader);
        }

        historyContainer.addView(mUILoader);
        initPresenter();

        return rootView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHistoryPresenter.unregisterViewCallback(this);
    }

    private void initPresenter() {
        mHistoryPresenter = HistoryPresenter.getInstance();
        mHistoryPresenter.registerViewCallback(this);


        mHistoryPresenter.getHistoryList();

        if (mUILoader != null) {
            mUILoader.updateStatus(UILoader.UIStatus.LOADING);
            mUILoader.setOnRetryClickListener(() ->{
                mUILoader.updateStatus(UILoader.UIStatus.LOADING);
                mHistoryPresenter.getHistoryList();
            });
        }
    }


    private View initSuccessView(LayoutInflater layoutInflater, ViewGroup container) {
        View view = layoutInflater.inflate(R.layout.history_success_layout, container, false);

        mHistory_rv = view.findViewById(R.id.history_success_historyRv);

        LinearLayoutManager manager = new LinearLayoutManager(container.getContext());
        mHistory_rv.setLayoutManager(manager);

        mHistoryAdapter = new DetailAdapter();
        mHistory_rv.setAdapter(mHistoryAdapter);
        mHistory_rv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top = UIUtil.dip2px(view.getContext(),2);
                outRect.bottom = UIUtil.dip2px(view.getContext(),2);
                outRect.left = UIUtil.dip2px(view.getContext(),2);
                outRect.right = UIUtil.dip2px(view.getContext(),2);
            }
        });


        mHistoryAdapter.setItemClickListener(new DetailAdapter.ItemClickListener() {
            @Override
            public void onItemClick(List<Track> detailData, int position) {
                PlayerPresenter.getPlayerPresenter().setPlayList(detailData, position);
                Intent intent = new Intent(HistoryFragment.this.getActivity(), PlayerActivity.class);
                HistoryFragment.this.startActivity(intent);
            }
        });

        mHistoryAdapter.setLongClickListener(new DetailAdapter.LongClickListener() {
            @Override
            public void onLongClick(List<Track> detailData, int position) {
                mCurrentTrack = detailData.get(position);

                mTrackDialog = new HistoryTrackDialog(view.getContext());
                mTrackDialog.setOnDialogActionClickListener(HistoryFragment.this);
                mTrackDialog.show();
            }
        });

        return view;

    }

    //============================ Callback for dialog  ====================================


    @Override
    public void onCancelClick() {
        if (mTrackDialog != null) {
            mTrackDialog.dismiss();
        }
    }

    @Override
    public void onConfirmClick(boolean isCheck) {
        if(isCheck){
            if (mUILoader != null) {
                mUILoader.updateStatus(UILoader.UIStatus.EMPTY);
            }
            mHistoryPresenter.cleanHistory();
        }else {
            mHistoryPresenter.deleteHistory(mCurrentTrack);
        }
    }

    //============================ Callback for Viewcallback   ====================================


    @Override
    public void onAddHistory(boolean isSuccess) {
        if(isSuccess){
            mHistoryPresenter.getHistoryList();
        }else{
            //Toast.makeText(BaseApplication.getAppContext(),"Fail to add history",Toast.LENGTH_SHORT).show();
            LogUtils.d(TAG, "-----Fail to add history");
        }
    }

    @Override
    public void onDelHistory(boolean isSuccess) {
        if(isSuccess){
            mHistoryPresenter.getHistoryList();
        }else{
            //Toast.makeText(BaseApplication.getAppContext(),"Fail to add history",Toast.LENGTH_SHORT).show();
            LogUtils.d(TAG, "-----Fail to del history");
        }
    }

    @Override
    public void onCleanHistory(boolean isSuccess) {
        if(isSuccess){
            mHistoryPresenter.getHistoryList();
        }else{
            //Toast.makeText(BaseApplication.getAppContext(),"Fail to add history",Toast.LENGTH_SHORT).show();
            LogUtils.d(TAG, "-----Fail to clean history");
        }
    }

    @Override
    public void onHistoryListLoad(List<Track> trackList) {
        if(trackList.size() > 0){
            mUILoader.updateStatus(UILoader.UIStatus.SUCCESS);
        }else {
            mUILoader.updateStatus(UILoader.UIStatus.EMPTY);
        }

        mHistoryAdapter.setData(trackList);
        mHistoryAdapter.notifyDataSetChanged();
    }

    @Override
    public void onHistoryListLoadError() {
        if (mUILoader != null) {
            mUILoader.updateStatus(UILoader.UIStatus.NETWORK_ERROR);
        }
    }
}
